import { ConfigureService } from '@app/configure';
import { JwtVerifyService } from '@app/jwt-verify';
import { CanActivate, ExecutionContext, Inject, Injectable } from '@nestjs/common';
import { UserService } from '../../user/user.service';

@Injectable()
export class AuthGuard implements CanActivate {
  @Inject()
  private readonly config:ConfigureService
  @Inject()
  private readonly jwt:JwtVerifyService
  @Inject()
  private readonly userService:UserService

  async canActivate(
    context: ExecutionContext,
  ): Promise<boolean> {
    let request = context.switchToHttp().getRequest()
    const route = request.route
    let path:string = route.path

    const white = this.config.get<string[]>('white.userClient')
    const routePrefix = this.config.get<string>('apiPrefix.userClient')
    if(routePrefix != undefined && routePrefix.length > 0) {
      path = path.substring(routePrefix.length + 1)
    }

    const token = request.headers.authorization
    if(!white.includes(path) && !token) return false
    
    if(token) {
      const jwtConfig = this.config.get('jwt.userClient.login')
      const payload = this.jwt.verify(token, {secret : jwtConfig.secret})
      if(!payload) return false

      const userId = (payload.key - jwtConfig.scale) / jwtConfig.scale

      let user = await this.userService.getFromCache(userId)
      if(!user) return false

      request.userId = userId
      request.user = user
    }

    if(request.headers['client-type']) {
      request.isWx = request.headers['client-type'] == 'wx'
      request.isAli = request.headers['client-type'] == 'ali'
      request.clientSource = request.isWx ? 1 : 2
    }

    
    
    return true;
  }
}